package com.rqf.ls.service.impl;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;
import org.springframework.stereotype.Service;

import com.oreilly.servlet.ParameterNotFoundException;
import com.rqf.common.base.PathManager;
import com.rqf.ls.service.IFileUploadService;
import com.server.common.util.FileUtil;

import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.EncodingAttributes;
import it.sauronsoftware.jave.InputFormatException;

@Service("FileUploadService")
public class FileUploadService implements IFileUploadService {
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	 /**
	 * 文件上传到服务器同时数据库记录
	 * @param projectName 工程名称
	 * @param userName 用户名
	 * @param saveType 文件保存分类
	 * @param fileFullName 文件全名
	 * @param decode 文件字节数组
	 * @param others 其他字段用Map包装传输
	 * @return 是否成功
	 * @author ServerZhang
	 * @throws ParameterNotFoundException 
	 * @date 2016年5月10日
	 */
	@Override
	public Boolean upload(String projectName, String userName, 
			String saveType, String fileFullName, 
			byte[] decode, Map<String, Object> others) throws ParameterNotFoundException{
		// 文件全名称，必须带后缀
		String[] imgSplit = fileFullName.split("\\.");
		if (imgSplit.length < 2) {
			throw new ParameterNotFoundException("缺少参数或参数不完整：照片名称！");
		}
		String imgName = imgSplit[0];
		String imgType = imgSplit[1];
		
		Boolean isSuccess = true;
		// 2、图片上传到服务器
		String filePath = PathManager.FILE_SAVEPATH;// 服务器文件地址
		String mappingPath = "\\"+projectName+"\\" + userName + "\\"+saveType+"";// 映射文件地址
		UUID uuid = UUID.randomUUID();
		filePath += mappingPath;
		File file = new File(filePath);
		if (!file.exists()) {
			file.mkdirs();
		}
		FileUtil.hex2File(decode, filePath + "\\" + uuid + "." + imgType);

		// 3、图片路径保存到数据库
		Map<String, Object> attrMap = new HashMap<String, Object>();
		attrMap.put("type", imgType);
		attrMap.put("fileName", imgName);
		attrMap.put("filePath", mappingPath);
		attrMap.put("uuid", uuid);
		attrMap.putAll(others);
		/*Set<String> keySet = others.keySet();
		for(String key : key){
			attrMap.put(key, others.get(key));
		}*/
		Map<String, Object> attrAddInfo = this.add(userName,
				attrMap);

		if (attrAddInfo.size() <= 0
				|| null == attrAddInfo.get("isSuccess")
				|| Integer.parseInt(attrAddInfo.get("isSuccess").toString()) <= 0) {
			isSuccess = false;
		} else {
		}
		return isSuccess;
	}
	
	@Override
	public String upload1(String projectName, String userName, 
			String saveType, String fileFullName, 
			byte[] decode, Map<String, Object> others) throws ParameterNotFoundException{
		// 文件全名称，必须带后缀
		String[] imgSplit = fileFullName.split("\\.");
		if (imgSplit.length < 2) {
			throw new ParameterNotFoundException("缺少参数或参数不完整：照片名称！");
		}
		String imgName = imgSplit[0];
		String imgType = imgSplit[1];
		
		// 2、图片上传到服务器
		String filePath = PathManager.FILE_SAVEPATH;// 服务器文件地址
		String mappingPath = "\\"+projectName+"\\" + userName + "\\"+saveType+"";// 映射文件地址
		UUID uuid = UUID.randomUUID();
		filePath += mappingPath;
		File file = new File(filePath);
		if (!file.exists()) {
			file.mkdirs();
		}
		FileUtil.hex2File(decode, filePath + "\\" + uuid + "." + imgType);

		// 3、图片路径保存到数据库
		Map<String, Object> attrMap = new HashMap<String, Object>();
		attrMap.put("type", imgType);
		attrMap.put("fileName", imgName);
		attrMap.put("filePath", mappingPath);
		attrMap.put("uuid", uuid);
		attrMap.putAll(others);
		/*Set<String> keySet = others.keySet();
		for(String key : key){
			attrMap.put(key, others.get(key));
		}*/
		Map<String, Object> attrAddInfo = this.add(userName,
				attrMap);

		if (attrAddInfo.size() <= 0
				|| null == attrAddInfo.get("isSuccess")
				|| Integer.parseInt(attrAddInfo.get("isSuccess").toString()) <= 0) {
			return "false";
		} else {
			return attrAddInfo.get("id").toString();
		}
	}
	
	@Override
	public Map<String, Object> add(String phoneNo, Map<String, Object> input){
		Map<String, Object> inputParamMap = new HashMap<String, Object>();
		inputParamMap.put("type", input.get("type"));//VARCHAR
		inputParamMap.put("fileName", input.get("fileName"));//VARCHAR
		inputParamMap.put("phoneNo", phoneNo);//VARCHAR
		inputParamMap.put("filePath", input.get("filePath"));//VARCHAR
		inputParamMap.put("uuid", input.get("uuid"));//VARCHAR
		inputParamMap.put("note", input.get("note"));//VARCHAR
		inputParamMap.put("saveType", input.get("saveType"));//VARCHAR
		inputParamMap.put("signUpId", input.get("signUpId"));//INT
		
		Map<String, Object> execute = new SimpleJdbcCall(jdbcTemplate)
			.withProcedureName("ATTACHMENT_ADD")
			.declareParameters(
						new SqlParameter("type",java.sql.Types.VARCHAR),
						new SqlParameter("fileName",java.sql.Types.VARCHAR),
						new SqlParameter("phoneNo",java.sql.Types.VARCHAR),
						new SqlParameter("filePath",java.sql.Types.VARCHAR),
						new SqlParameter("uuid",java.sql.Types.VARCHAR),
						new SqlParameter("note",java.sql.Types.VARCHAR),
						new SqlParameter("saveType",java.sql.Types.VARCHAR),
						new SqlParameter("signUpId",java.sql.Types.INTEGER),
						new SqlOutParameter("id",java.sql.Types.INTEGER),
						new SqlOutParameter("isSuccess",java.sql.Types.INTEGER)
			).execute(inputParamMap);
		return execute;	
	}
	/*@Override
	public Boolean update(Integer id, Map<String, Object> inputMap){
		String tableName = "QUESTION";
		String whereStr = "id="+id;
		Boolean isSuccess = jdbcService.update(tableName, inputMap, whereStr);
		return isSuccess;
		StringBuffer updateStr = new StringBuffer();
		//String sql = "Update QUESTION set questiontypeid='111',createuser='sbb',content='%s' where id=%s";
		String sql = "Update QUESTION set %s where id=%s";
		Set<String> keySet = inputMap.keySet();
		for(String key : keySet){
			if (updateStr.length() > 0) {
				updateStr.append(",");
			}
			updateStr.append(key).append("='").append(inputMap.get(key)).append("'");
		}
		
		String format = String.format(sql, updateStr.toString(),id);
		Boolean isSuccess = true;
		try {
			jdbcTemplate.execute(format);
		} catch (Exception e) {
			isSuccess = false;
		}
		return isSuccess;
	}
	
	@Override
	public Boolean delete(Integer id){
		String sql = "Delete from question where id=%s";
		String format = String.format(sql,id);
		Boolean isSuccess = true;
		try {
			jdbcTemplate.execute(format);
		} catch (Exception e) {
			isSuccess = false;
		}
		return isSuccess;
	}*/

	@Override
	public String getFilePathById(String attachmentId) {
		String path = "";
		String sql = "Select * from ATTACHMENT where id='"+attachmentId+"'";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
		if (list.size() > 0) {
			Map<String, Object> map = list.get(0);
			Object pathObj = map.get("FILEPATH");
			Object uuidObj = map.get("UUID");
			Object typeObj = map.get("TYPE");
			if (pathObj != null && uuidObj != null && typeObj != null) {
				path += pathObj.toString() +"\\" + uuidObj.toString()
						+"."+ typeObj.toString();
			}
		}
		return path;
	}

	@Override
	public void amrChangeToMp3(String sourcePath, String targetPath) {
		File source = new File(PathManager.FILE_SAVEPATH+sourcePath);
		File target = new File(PathManager.FILE_SAVEPATH+targetPath);
		AudioAttributes audio = new AudioAttributes();
		Encoder encoder = new Encoder();

		audio.setCodec("libmp3lame");
		EncodingAttributes attrs = new EncodingAttributes();
		attrs.setFormat("mp3");
		attrs.setAudioAttributes(audio);

		try {
			encoder.encode(source, target, attrs);
		} catch (IllegalArgumentException e) {
			//e.printStackTrace();
		} catch (InputFormatException e) {
			//e.printStackTrace();
		} catch (EncoderException e) {
			//e.printStackTrace();
		}
	}
	
	@Override
	public String getFileByPhoneNoAndSaveType(String phoneNo,String saveType) {
		String path = "";
		String sql = "Select * from ATTACHMENT where saveType='%s' %s order by createTime desc";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(String
				.format(sql, saveType , "and phoneNo='" + phoneNo +"'"));
		if (list.size() > 0) {
			Map<String, Object> map = list.get(0);
			Object pathObj = map.get("FILEPATH");
			Object uuidObj = map.get("UUID");
			Object typeObj = map.get("TYPE");
			if (pathObj != null && uuidObj != null && typeObj != null) {
				path += pathObj.toString() +"\\" + uuidObj.toString()
						+"."+ typeObj.toString();
			}
		}
		return path;
	}

}
